from typing import Dict, Any, List
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from .base_model import BaseLLMModel
from config import Config
from config.thresholds import ModelThresholds
from monitoring import trace_function
import logging

logger = logging.getLogger(__name__)

class CommitMessageModel(BaseLLMModel):
    """Commit Message汇总生成模型"""
    
    def __init__(self, model_name: str = None):
        super().__init__(model_name, temperature=ModelThresholds.MIN_TEMPERATURE)  # 降低温度以获得更一致的输出
    
    def _setup_chain(self):
        """设置commit message汇总生成的LangChain链"""
        self.commit_prompt_template = ChatPromptTemplate.from_messages([
            ("system", "你是一个专业的Git commit message汇总助手。"),
            ("human", Config.COMMIT_PROMPT)
        ])
        self.chain = self.commit_prompt_template | self.llm | StrOutputParser()
    
    def generate_response(self, **kwargs) -> str:
        """实现抽象方法，生成commit message"""
        summaries = kwargs.get("summaries", [])
        return self.generate_summary_commit_message(summaries)
    
    @trace_function(name="commit_message_generation")
    def generate_summary_commit_message(self, summaries: List[Dict[str, Any]], user_id: str = None, session_id: str = None) -> str:
        """根据多个summary信息生成一条汇总的commit message"""
        try:
            logger.info("=== CommitMessageModel.generate_summary_commit_message 开始 ===")
            logger.info(f"📋 接收到的参数 - user_id: {user_id}, session_id: {session_id}")
            logger.info(f"📊 summaries数量: {len(summaries)}")
            logger.info(f"开始处理 {len(summaries)} 个summary")
            
            # 构建汇总信息
            summary_info = self._build_summary_info(summaries)
            logger.info(f"构建的汇总信息: {summary_info}")
            
            # 调用LLM生成，传递追踪参数
            logger.info("调用LLM生成commit message...")
            logger.info(f"🔍 准备调用invoke_chain_with_langfuse")
            logger.info(f"📋 传递的参数 - user_id: {user_id}, session_id: {session_id}")
            
            result = self.invoke_chain_with_langfuse(self.chain, {
                "file_path": summary_info["file_path"],
                "change_type": summary_info["change_type"],
                "change_content": summary_info["change_content"],
                "diff_content": summary_info["diff_content"]
            }, user_id=user_id, session_id=session_id)
            
            logger.info(f"LLM生成结果: {result}")
            return result
        except Exception as e:
            logger.error(f"生成汇总commit message时发生错误: {str(e)}")
            return self._handle_error(e, "生成汇总commit message")
    
    def _build_summary_info(self, summaries: List[Dict[str, Any]]) -> Dict[str, str]:
        """构建汇总信息"""
        if not summaries:
            logger.warning("没有收到summary数据")
            return {
                "file_path": "无变更",
                "change_type": "无变更",
                "change_content": "无变更",
                "diff_content": ""
            }
        
        # 按order排序
        sorted_summaries = sorted(summaries, key=lambda x: x.get("order", 0))
        logger.info(f"按order排序后的summaries: {sorted_summaries}")
        
        # 提取所有summary内容，这些应该是commit messages
        summary_contents = [item.get("summary", "") for item in sorted_summaries]
        logger.info(f"提取的summary内容: {summary_contents}")
        
        # 将多个commit messages格式化为列表形式
        commit_messages_list = []
        for i, content in enumerate(summary_contents):
            # 如果内容已经是commit message格式，直接使用
            if content.strip().startswith('`') and content.strip().endswith('`'):
                # 移除反引号
                clean_content = content.strip()[1:-1]
                commit_messages_list.append(f"- `{clean_content}`")
            else:
                # 如果不是标准格式，直接添加
                commit_messages_list.append(f"- `{content}`")
        
        # 将所有commit messages组合成一个字符串
        change_content = "\n".join(commit_messages_list)
        
        logger.info(f"格式化后的commit messages: {change_content}")
        
        # 构建汇总描述
        file_path = f"多个文件({len(summaries)}个改进)"
        change_type = "代码改进"  # 这个字段在新的prompt中不再使用，但保持兼容性
        diff_content = f"汇总了{len(summaries)}个commit messages"
        
        result = {
            "file_path": file_path,
            "change_type": change_type,
            "change_content": change_content,
            "diff_content": diff_content
        }
        
        logger.info(f"构建的汇总信息: {result}")
        return result
    
    def generate_structured_summary(self, summaries: List[Dict[str, Any]], user_id: str = None, session_id: str = None) -> Dict[str, Any]:
        """生成结构化的汇总commit message"""
        logger.info("=== CommitMessageModel.generate_structured_summary 开始 ===")
        logger.info(f"📋 接收到的参数 - user_id: {user_id}, session_id: {session_id}")
        logger.info(f"📊 summaries数量: {len(summaries)}")
        logger.info(f"📝 summaries内容: {summaries}")
        
        summary_message = self.generate_summary_commit_message(summaries, user_id=user_id, session_id=session_id)
        
        result = self._add_metadata(
            summary_message,
            commit_count=len(summaries),
            files_affected=len(summaries),  # 每个summary对应一个改进
            change_types=list(set(self._extract_change_types(summaries)))
        )
        
        logger.info(f"最终生成的结构化结果: {result}")
        return result
    
    def _extract_change_types(self, summaries: List[Dict[str, Any]]) -> List[str]:
        """提取变更类型"""
        change_types = []
        for summary in summaries:
            content = summary.get("summary", "").lower()
            if "安全" in content or "验证" in content:
                change_types.append("安全修复")
            elif "性能" in content or "缓存" in content:
                change_types.append("性能优化")
            elif "重构" in content or "代码" in content:
                change_types.append("代码重构")
            elif "bug" in content or "修复" in content:
                change_types.append("bug修复")
            elif "功能" in content or "新增" in content:
                change_types.append("功能增强")
            else:
                change_types.append("代码改进")
        return change_types 